# coding:utf-8
from __future__ import print_function
from tkinter import Variable
from flask import Flask, render_template, request, redirect, url_for, make_response,jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time

import numpy as np
from PIL import Image
import torch
import torch.cuda
import torch.nn
import torchvision.models as models
import torchvision.transforms as transforms
import numpy as np
import cv2
import inference  #导入推理工具包
from inference import get_model,deal_img,cls_inference,feature_extract
import scipy.misc
import numpy as np
from datetime import timedelta
from label_level2 import under_jeans,under_skirt,under_sporty,under_suit,upper_casual,upper_coat,upper_hoodie,upper_sporty,upper_suit,whole_dress
#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
 
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
 
app = Flask(__name__)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)
#标签数组:存放两级标签数组，第一级为字符串，第二级为存放对应链接
label_level_1 = ['under_jeans','under_skirt','under_sporty','under_suit','upper_casual','upper_coat','upper_hoodie','upper_sporty','upper_suit','whole_dress ']
label_level_2 = [under_jeans,under_skirt,under_sporty,under_suit,upper_casual,upper_coat,upper_hoodie,upper_sporty,upper_suit,whole_dress ]
'''
@param

@input:cls_label也就是预测的Label
@output:按顺序返回对应label的三个链接
@在label_level2.py里面存放着二级标签
'''
def judge(cls_label):#判断类别，再给出对应的链接
    for index in range(len(label_level_1)):
        if label_level_1[index] == label_level_1[cls_label]:#
            return label_level_2[index][0],label_level_2[index][1],label_level_2[index][2]

# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        f = request.files['file']
 
        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG、jpg、JPG、bmp"})
 
        user_input = request.form.get("name")
 
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
 
        # upload_path = os.path.join(basepath, 'static/images', secure_filename(f.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        upload_path = os.path.join(basepath, 'static/images','test.jpg')  #注意：没有的文件夹一定要先创建，不然会提示没有该路径
        f.save(upload_path)

        
        # 使用Opencv转换一下图片格式和名称
        # img = cv2.imread(upload_path)
        # cv2.imwrite(os.path.join(basepath,'static\images', 'test.jpg'), img)

        '''
        image = image.resize((28,28))
        image = np.copy(image) # 这一句    
        imgs = np.array(image) / 255		# 归一化
        imgs = imgs.reshape([-1,28,28,1])
        model = load_model('my_model.h5')

        result = model.predict(imgs)
        result = label[np.argmax(result)]
        print(label[np.argmax(result)])
        # r_image = yolo.detect_image(image)
        # r_image.show()
        # imgs.save(upload_path)
        ##keras—fminist推理代码
        '''
        # image = Image.open(upload_path)
        # image_path="./dataset_dir/train/whole_dress/dress_abstract (7).jpg"
        model = get_model()
        cls_label = cls_inference(model,upload_path)
        print(cls_label)
        # variable_1 = "https://aistudio.baidu.com/paddle/forum"
        result = label_level_1[cls_label]
        variable_1,variable_2,variable_3=judge(cls_label)
 
        return render_template('upload_ok.html'
        ,userinput=user_input
        ,variable=result#前端界面显示的种类
        ,variable_1=variable_1#种类链接一
        ,variable_2=variable_2#种类链接二
        ,variable_3=variable_3#种类链接三
        ,val1=time.time())
        
 
    return render_template('upload.html')
 
 
if __name__ == '__main__':
    # app.debug = True
    app.run(host='0.0.0.0', port=8987, debug=True)